package com.ybbase.framework.controller.system;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.common.collect.Sets;
import com.ybbase.framework.base.controller.BaseController;
import com.ybbase.framework.base.model.ResponseBean;
import com.ybbase.framework.common.constant.CommonResultCode;
import com.ybbase.framework.common.enums.LogFunType;
import com.ybbase.framework.common.enums.LogType;
import com.ybbase.framework.common.util.*;
import com.ybbase.framework.model.po.system.ActiveCode;
import com.ybbase.framework.model.po.system.Organization;
import com.ybbase.framework.model.po.system.User;
import com.ybbase.framework.model.vo.JwtVO;
import com.ybbase.framework.service.system.ActiveCodeService;
import com.ybbase.framework.service.system.LogService;
import com.ybbase.framework.service.system.OrganizationService;
import com.ybbase.framework.service.system.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * @author cg
 * @date 2019-07-16 11:35
 * @DEC
 */
@RestController
@RequestMapping(value = "/")
@Api("登录管理")
public class LoginController extends BaseController {

    private static final String MAIN_URL = "/api/templates/start/index.html";
    private static final Logger LOGGER = LogManager.getLogger(LoginController.class);
    @Value("${mossCode}")
    private String mossCode;

    @Resource
    private DefaultKaptcha captchaProducer;

    @Autowired
    UserService userService;

    @Autowired
    ActiveCodeService activeCodeService;

    @Autowired
    private LogService logService;


    @Autowired
    private OrganizationService organizationService;

    @GetMapping(value = "/")
    public void getToMain(HttpServletResponse response) throws Exception {
        response.sendRedirect(MAIN_URL);
    }

    /**
     * 登录验证码SessionKey
     */
    public static final String LOGIN_VALIDATE_CODE = "login_validate_code";

    /**
     * @author cg
     * 登入
     */
    @GetMapping(value = "/login", produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "登录方法", notes = "登录方法", response = ResponseBean.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "loginName", value = "用户登录名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String"),
    })
    public ResponseBean login(@RequestParam String loginName, @RequestParam String password,
                               HttpServletRequest request) {
        try {
//            String loginValidateCode = getValidateSessionKey();
//            if (loginValidateCode == null || !loginValidateCode.equals(validateCode)) {
//                return new ResponseBean(CommonResultCode.FAIL.getCode(), "验证码输入错误，请查正后重新输入", null);
//            }
            User user = userService.getUserByLoginName(loginName);
            short state = 1;
            if (user != null) {
                String ip = IpUtil.getIp(request);
                user.setLoginIp(ip);
                user.setLoginFlag(1);
                user.setLoginDate(new Date());
                userService.updateById(user);
                if (state == user.getDelFlag()) {
                    //验证冻结
                    return new ResponseBean(CommonResultCode.FAIL.getCode(), "用户已冻结", null);
                } else if (user.getPassword().equals(DESUtil.encryptBasedDes(password))) {
                    JwtVO jwtVO = new JwtVO();
                    jwtVO.setUserId(user.getId());
                    jwtVO.setUserName(user.getName());
                    jwtVO.setToken(userService.generateJwtToken(user.getId()));
                    Organization organization = getOrganizationByUserId(user.getId().toString());
                    Organization oldOrgan = organizationService.getById(organization.getParentId());
                    jwtVO.setOrganId(organization.getId());
                    jwtVO.setOrganName(oldOrgan!=null?oldOrgan.getName()+"/"+organization.getName():organization.getName());
//                    logService.saveLog(LogType.Login.getEnumKey(), LogFunType.DEFAULT.getEnumKey());
                    return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "登录" + CommonResultCode.SUCCESS.getMsg(), jwtVO);
                } else {
                    return new ResponseBean(CommonResultCode.FAIL.getCode(), "用户名或密码输入错误", null);
                }
            } else {
                return new ResponseBean(CommonResultCode.FAIL.getCode(), "用户名或密码输入错误", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
            return new ResponseBean(500, "查询异常！", null);
        }
    }

    /**
     * 登出方法
     *
     * @param request
     * @return ResponseBean
     * @author cg
     * @date 2019-12-01 21:15
     * @since cloud2.0
     */
    @GetMapping(value = "/logout", produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "登出方法", notes = "登出方法", response = ResponseBean.class)
    public ResponseBean logout(HttpServletRequest request) {
        try {
            User user = this.getAtUser(getTokenString(request));
            if (user != null) {
                user.setLoginFlag(0);
                userService.updateById(user);
            }
//            logService.saveLog(LogType.Logout.getEnumKey(), LogFunType.DEFAULT.getEnumKey());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "退出" + CommonResultCode.SUCCESS.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "更新异常！");
        }
    }

    /**
     * 输入激活码
     *
     * @param code 激活码
     * @return ResponseBean
     * @author cg
     * @date 2019-12-24 13:27
     * @since cloud2.0
     */
    @GetMapping("/setCode")
    @ApiOperation(value = "输入激活码", notes = "输入激活码", response = ResponseBean.class)
    public ResponseBean setCode(@RequestParam String code) {
        try {
            EncryptUtil encryptUtil = EncryptUtil.getInstance();
            String codes = encryptUtil.aseDecode(code, mossCode);
            String[] codesCg = codes.split("[|]");
            String ipAddress = MachineUtil.getLocalIP();
            String macAddress = MachineUtil.getMacId();
            if (!ipAddress.equals(codesCg[0]) || !macAddress.equals(codesCg[1])) {
                return new ResponseBean(CommonResultCode.FAIL.getCode(), "安装激活码的机器有变化请查证后重新输入！", null);
            }
            if (DateUtil.parseDateTime(codesCg[3]).before(new Date())) {
                return new ResponseBean(CommonResultCode.FAIL.getCode(), "激活码已过期，请联系管理员！", null);
            }
            QueryWrapper<ActiveCode> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ActiveCode::getEncryption, code);
            List<ActiveCode> list = activeCodeService.list(queryWrapper);
            if (list != null && !list.isEmpty()) {
                return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "激活码输入正常" + CommonResultCode.SUCCESS.getMsg());
            }
            ActiveCode activeCode = new ActiveCode();
            activeCode.setEncryption(code);
            activeCode.setIpAddress(codesCg[0]);
            activeCode.setMacAddress(codesCg[1]);
            activeCode.setStartdate(DateUtil.parseDateTime(codesCg[2]));
            activeCode.setEnddate(DateUtil.parseDateTime(codesCg[3]));
            activeCodeService.save(activeCode);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "激活码输入正常" + CommonResultCode.SUCCESS.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "激活码异常，请查证后重新输入！");
        }
    }

    /**
     * 验证软件是否已经过了有效期
     *
     * @author cg
     * @date 2019-12-24 13:33
     * @since cloud2.0
     */
    @GetMapping("/validateSeacte")
    @ApiOperation(value = "验证软件是否已经过了有效期", notes = "验证软件是否已经过了有效期", response = ResponseBean.class)
    public ResponseBean validateSeacte(HttpServletResponse response) {
        // 验证软件是否已经过了有效期
        QueryWrapper<ActiveCode> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().le(ActiveCode::getStartdate, new Date());
        queryWrapper.lambda().gt(ActiveCode::getEnddate, new Date());
        List<ActiveCode> activeCodes = activeCodeService.list(queryWrapper);
        try {
            ActiveCode activeCode = new ActiveCode();
            if (activeCodes != null && !activeCodes.isEmpty()) {
                activeCode = activeCodes.get(0);
            } else {
                return new ResponseBean(CommonResultCode.FAIL.getCode(), "请输入激活码！", null);
            }
            String ipAddress = MachineUtil.getLocalIP();
            String macAddress = MachineUtil.getMacId();
            EncryptUtil encryptUtil = EncryptUtil.getInstance();
            String[] codesCg = encryptUtil.aseDecode(activeCode.getEncryption(), mossCode).split("[|]");
            if (!ipAddress.equals(codesCg[0]) || !macAddress.equals(codesCg[1])) {
                return new ResponseBean(CommonResultCode.FAIL.getCode(), "安装激活码的机器有变化请查证后重新输入！", null);
            }
            if (DateUtil.parseDateTime(codesCg[3]).before(new Date())) {
                return new ResponseBean(CommonResultCode.FAIL.getCode(), "激活码已过期，请联系管理员！", null);
            }
        }catch (Exception e){
            e.printStackTrace();
            LOGGER.error(e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "数据出现错误，请联系管理员！", null);
        }
        return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "激活码有效！" + CommonResultCode.SUCCESS.getMsg());
    }

    /**
     * 生成验证码
     *
     * @param request
     * @param response
     * @author cg
     * @date 2019-12-23 23:50
     * @since cloud2.0
     */
//    @RequestMapping(value = {"/loginValidateCode"})
//    public void loginValidateCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        this.validateCode(request, response, captchaProducer, LOGIN_VALIDATE_CODE);
//    }


}
